const assigModel = require('../models/assigModel')

const fs = require('fs');
const path = require('path');

// 添加作业--布置作业
exports.add_c = async (req, res) => {
    let { title, description, class_id, set_date, due_date, difficulty, teacher, picture } = req.body
    try {
        let results = await assigModel.add(title, description, class_id, set_date, due_date, difficulty, teacher, picture)
        console.log(results)
        res.json({ code: 0, msg: "作业布置成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 删除作业--软删除
exports.del_f = async (req, res) => {
    let { id } = req.query
    try {
        let results = await assigModel.del_f(id)
        console.log(results)
        res.json({ code: 0, msg: "作业禁用成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
exports.start = async (req, res) => {
    let { id } = req.query
    try {
        let results = await assigModel.start_state(id)
        console.log(results)
        res.json({ code: 0, msg: "作业启用成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 删除作业--真删除
exports.del_t = async (req, res) => {
    let { id } = req.query
    try {
        let results = await assigModel.del_t(id)
        console.log(results)
        res.json({ code: 0, msg: "作业记录删除成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 作业查看-获取数据
exports.get = async (req, res) => {
    let { id } = req.query
    try {
        let results = await assigModel.get(id)
        console.log(results)
        res.json({ code: 0, msg: "作业查看-获取数据成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 修改更新作业-设置数据
exports.set = async (req, res) => {
    let { id, title, description, class_id, set_date, due_date, difficulty, teacher, picture } = req.body
    try {
        let results = await assigModel.set(id, title, description, class_id, set_date, due_date, difficulty, teacher, picture)
        console.log(results)
        res.json({ code: 0, msg: "作业查看-设置数据成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 作业列表搜索
exports.list = async (req, res) => {
    let { title, class_id, teacher_id, program_id, difficulty, set_date_start, set_date_end, page_size, page } = req.query
    try {
        let results = await assigModel.list(title, class_id, teacher_id, program_id, difficulty, set_date_start, set_date_end, Number(page_size), Number(page))
        console.log(results)
        res.json({ code: 0, msg: "作业列表搜索数据成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 文件上传
exports.uploads = async (req, res) => {
    // 获取请求头中的token
    const token = req.headers.authorization;

    // 检查token是否存在
    if (!token) {
        return res.status(401).json({ code: 1, msg: "无token，请先登录" });
    }

    // 获取上传的文件信息
    console.log("aaaa", req.files)
    let { id } = req.body
    let one_f = req.files.file;

    var originalFilename = one_f.originalFilename;

    var file_path = one_f.path;

    try {
        // 读取文件内容并保存到新位置
        if (file_path) {
            let date = new Date();
            let new_name = date.getTime() + path.extname(originalFilename);

            // 生成网络可访问的URL
            const baseUrl = 'http://localhost:3000'; // 你的服务器地址
            const fileUrl = `${baseUrl}/uploads/${new_name}`;

            let new_file_name = 'public/uploads/' + new_name;
            console.log("图片路径：：：：：：：：", new_file_name, fileUrl)
            // 把图片处理好的路径new_file_name存到名为user的数据库的picture的字段里
            const image = await assigModel.uploads(new_file_name, Number(id), file_path);

            // console.log(image)
            // res.json({ code: 0, msg: "图片上传成功！", image })
            fs.rename(file_path, new_file_name, (err) => {
                if (err) {
                    console.log(err)
                    res.json({ status: -1, msg: err.message });
                } else {
                    res.json({
                        msg: "文件上传完成", code: 0, data: {
                            fileName: new_file_name,
                            ext: path.extname(new_file_name)
                        },
                        image
                    })
                }
            });
        } else {
            res.json({
                status: -2,
                msg: "图片未找到"
            })
        }
    } catch (error) {
        console.log('Error uploading image:', error);
        res.json({ code: 1, msg: error.message });
    }
}

// 文件删除
exports.deleteImage = async (req, res) => {
    // 鉴权验证
    const token = req.headers.authorization;
    if (!token) {
        return res.status(401).json({ code: 1, msg: "无token，请先登录" });
    }
    // public/uploads/1742372086892.jpg
    try {
        // 参数校验
        const { id, filePath } = req.body;
        const delete_url = `../${filePath}`
        if (!filePath) {
            return res.status(400).json({
                code: 2,
                msg: "缺少必要参数: filePath"
            });
        }

        // 安全路径校验
        // const safePath = path.normalize(filePath).replace(/^(\.\.[\/\\])+/g, '');
        // const fullPath = path.join(__dirname, '../public/uploads', safePath);

        if (!fullPath.startsWith(path.join(__dirname, '../public/uploads'))) {
            return res.status(403).json({
                code: 3,
                msg: "非法文件路径"
            });
        }

        // 数据库记录删除
        const deleteResult = await assigModel.deleteByPath(Number(id));
        // 证明存在此数据--此作业
        if (!deleteResult.changedRows) {
            return res.status(404).json({
                code: 4,
                msg: "数据库记录不存在"
            });
        }

        // 物理文件删除
        // fs.unlinkSync(delete_url);
        await fs.promises.access(delete_url, fs.constants.F_OK); // 异步操作，不会阻塞代码
        await fs.promises.unlink(delete_url);

        res.json({
            code: 0,
            msg: "文件删除成功",
            data: {
                deletedPath: safePath,
                timestamp: new Date().toISOString()
            }
        });

    } catch (error) {
        // 错误分类处理
        if (error.code === 'ENOENT') {
            return res.status(404).json({
                code: 5,
                msg: "文件不存在"
            });
        }

        console.error('删除操作失败:', error);
        res.status(500).json({
            code: 9,
            msg: "服务器内部错误",
            detail: error.message
        });
    }
};

// 作业批改--of--学生列表的显示
exports.student_list = async (req, res) => {
    let { id, class_id, name, page_size, page } = req.query
    try {
        let results = await assigModel.student_list(id, class_id, name, Number(page_size), Number(page))
        console.log(results)
        res.json({ code: 0, msg: "学生列表的显示数据成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 作业批改，给对应的学生的对应作业评分
exports.correct = async (req, res) => {
    // student_id时学生的id
    let { assignment_id, student_id, status, submitted_at, score, comment } = req.body
    // 当前时间戳
    let create_time = Date.now()
    try {
        let results = await assigModel.correct(assignment_id, student_id, status, submitted_at, score, comment, create_time)
        console.log(results)
        res.json({ code: 0, msg: "作业批改成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 作业分析--表格
exports.homework_table = async (req, res) => {
    let { name, classes_id, programs_id, page, page_size } = req.query
    try {
        let results = await assigModel.homework_table(name, classes_id, programs_id, Number(page), Number(page_size))
        console.log(results)
        res.json({ code: 0, msg: "作业分析-表格数据请求成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 学生作业提交趋势表
exports.sub_trend = async (req, res) => {
    let { title, class_id, program_id, start_time, end_time } = req.query
    // // 创建一个Date对象
    // var date1 = new Date(start_time);
    // var date2 = new Date(end_time);
    // // 获取时间戳（毫秒）
    // var start_date = date1.getTime();
    // var end_date = date2.getTime();
    try {
        let results = await assigModel.sub_trend(title, class_id, program_id, start_time, end_time)
        console.log(results)
        res.json({ code: 0, msg: "学生作业提交趋势表数据请求成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}
// 作业难度分布图
exports.difficulty = async (req, res) => {
    let { class_id, program_id } = req.query
    try {
        let results = await assigModel.difficulty(class_id, program_id)
        console.log(results)
        res.json({ code: 0, msg: "作业难度分布图数据请求成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}

// 所有作业
exports.allwork = async (req, res) => {
    let { class_id, program_id } = req.query
    try {
        let results = await assigModel.allwork(Number(class_id), Number(program_id))
        console.log(results)
        res.json({ code: 0, msg: "所有作业-获取数据成功！", results })
    } catch (error) {
        console.log(error)
        res.json({ code: 0, msg: error })
    }
}